package org.yaac.client.util;

import org.yaac.shared.YaacAutoBeanFactory;
import org.yaac.shared.file.FileDownloadPath;
import org.yaac.shared.file.FileDownloadPath.Type;

import com.google.gwt.core.client.GWT;
import com.google.web.bindery.autobean.shared.AutoBean;
import com.google.web.bindery.autobean.shared.AutoBeanCodex;

/**
 * AutoBeanUtil used in client side to deserialize
 * 
 * @author Max Zhu (thebbsky@gmail.com)
 *
 */
public class AutoBeanUtil {

	// use GWT.create for client side
	private static final YaacAutoBeanFactory abf = GWT.create(YaacAutoBeanFactory.class);
	
	/**
	 * @param <T>
	 * @param clazz
	 * @param o
	 * @return
	 */
	public static <T> String encode(Class<T> clazz, T o) {
		AutoBean<T> source = abf.create(clazz, o);
		return AutoBeanCodex.encode(source).getPayload();
	}
	
	/**
	 * @param <T>
	 * @param clazz
	 * @param encodedStr
	 * @return
	 */
	public static <T> T decode(Class<T> clazz, String encodedStr) {
		return AutoBeanCodex.decode(abf, clazz, encodedStr).as();
	}
	
	/**
	 * @param blobKeyString
	 * @return
	 */
	public static FileDownloadPath blobDownloadPath(String blobKeyString) {
		FileDownloadPath path = abf.fileDownloadPath().as();
		path.setType(Type.BLOBSTORE_BLOB);
		path.setKeyStr(blobKeyString);
		path.setFieldName(null);
		path.setIndex(null);
		return path;
	}
	
	/**
	 * @param blobKeyString
	 * @return
	 */
	public static String blobDownladPathString(String blobKeyString) {
		FileDownloadPath path = blobDownloadPath(blobKeyString);
		return encode(FileDownloadPath.class, path);
	}
	
	/**
	 * @param cacheKey
	 * @param size
	 * @return
	 */
	public static FileDownloadPath cacheDownloadPath(String cacheKey, Integer size) {
		FileDownloadPath path = abf.fileDownloadPath().as();
		path.setType(Type.MEMCACHE);
		path.setKeyStr(cacheKey);
		path.setFieldName(null);
		path.setIndex(null);
		path.setSize(size);
		return path;
	}
	
	/**
	 * @param cacheString
	 * @param size
	 * @return
	 */
	public static String cacheDownladPathString(String cacheString, Integer size) {
		FileDownloadPath path = cacheDownloadPath(cacheString, size);
		return encode(FileDownloadPath.class, path);
	}
}
